#项目名
PROJECT_NAME := "kube-sync"
#入口文件的路径
MAIN_FILE_PAHT := "main.go"
#编译完成的文件名
OUTPUT_NAME := "kube-sync"
#整个项目的包名
PKG := "gitee.com/hexug/kube-sync"
# 版本号
VERSION := "v0.4.2"

#获取模块的文件目录
MOD_DIR := $(shell go env GOPATH)/pkg/mod
PKG_LIST := $(shell go list ${PKG}/... | grep -v /vendor/ | grep -v redis)
GO_FILES := $(shell find . -name '*.go' | grep -v /vendor/ | grep -v _test.go)


#获取当前分支
BUILD_BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
#获取当前的commit号
BUILD_COMMIT := ${shell git rev-parse HEAD}
#获取当前的时间
BUILD_TIME := ${shell date '+%Y-%m-%d %H:%M:%S'}
#获取go的版本
BUILD_GO_VERSION := $(shell go version | grep -o  'go[0-9].[0-9].*')
#获取version的包名
VERSION_PATH := "${PKG}/version"


.PHONY: all dep lint vet test test-coverage build clean

all: build

dep: ## Get the dependencies
	@go mod tidy

lint: ## Lint Golang files
	@golint -set_exit_status ${PKG_LIST}

vet: ## Run go vet
	@go vet ${PKG_LIST}

test: ## Run unittests
	@go test -short ${PKG_LIST}

test-coverage: ## Run tests with coverage
	@go test -short -coverprofile cover.out -covermode=atomic ${PKG_LIST}
	@cat cover.out >> coverage.txt

build: dep ## Build the binary file
	@go build -a -o dist/${OUTPUT_NAME}  ${MAIN_FILE}

linux: dep
	@echo "Building Linux amd64 binary..."
	@GOOS=linux GOARCH=amd64 go build -a -o dist/${OUTPUT_NAME}-${VERSION}-Linux-amd64 \
          -ldflags "-s -w" -ldflags "-X '${VERSION_PATH}.GIT_TAG=${VERSION}' -X '${VERSION_PATH}.GIT_BRANCH=${BUILD_BRANCH}' -X '${VERSION_PATH}.GIT_COMMIT=${BUILD_COMMIT}' -X '${VERSION_PATH}.BUILD_TIME=${BUILD_TIME}' -X '${VERSION_PATH}.GO_VERSION=${BUILD_GO_VERSION}'" ${MAIN_FILE}

windows: dep
	@echo "Building Windows amd64 binary..."
	@GOOS=windows GOARCH=amd64 go build -a -o dist/${OUTPUT_NAME}-${VERSION}-Windows-amd64.exe \
          -ldflags "-s -w" -ldflags "-X '${VERSION_PATH}.GIT_TAG=${VERSION}' -X '${VERSION_PATH}.GIT_BRANCH=${BUILD_BRANCH}' -X '${VERSION_PATH}.GIT_COMMIT=${BUILD_COMMIT}' -X '${VERSION_PATH}.BUILD_TIME=${BUILD_TIME}' -X '${VERSION_PATH}.GO_VERSION=${BUILD_GO_VERSION}'" ${MAIN_FILE}

init: dep ## Inital project
	@go run main.go init

run: ## Run Server
	@KUBECONFIG=etc/config go run main.go

clean: ## Remove previous build
	@go clean .
	@rm -f dist/${PROJECT_NAME}

tag: ## Create git tag  with the latest commit message and push it
	@printf "Create git tag $(VERSION) with the latest commit message and push it\n"
	@if git rev-parse "$(VERSION)" >/dev/null 2>&1; then \
    		echo "Tag $(VERSION) already exists!"; \
    		exit 1; \
	fi
	@commit_msg=$$(git log -1 --pretty=%B); \
	git tag -a "$(VERSION)" -m "$$commit_msg"; \
	git push origin "$(VERSION)"

help: ## Display this help screen
	@grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'